<template>
  <div class="comment-container">
    <!-- 标题区域 -->
    <div class="comment-header">
      <span class="comment-title">快知评论</span>
      <div class="comment-counts">
        <span class="comment-follow">评论数 {{page.total}}</span>
        <span class="comment-join">点击人数 1446</span>
      </div>
    </div>
    
    <!-- 评论框 -->
    <div class="comment-form">
      <textarea placeholder="写下你的评论..." v-model="commentContext"></textarea>
      <div class="form-footer">
        <div class="comment-notice">
          网友评论仅供其表达个人看法，并不表明网易立场。
        </div>
        <button class="comment-submit" @click="submitComment">提交评论</button>
      </div>
    </div>
    
    <!-- 评论列表 -->
    <div class="comment-list">
      <div 
        v-for="(comment, index) in comments" 
        :key="index" 
        class="comment-item"
      >
        <div class="comment-user">
          <img :src="comment.userPic" alt="用户头像" class="comment-avatar">
          <span class="comment-username">{{ comment.userName }}</span>
        </div>
        <div class="comment-content">
          {{ comment.commentContent }}
        </div>
        <div class="comment-footer">
          <div class="comment-time">{{ comment.commentTime }}</div>
          <div class="comment-actions">
            <span class="comment-action comment-up" @click="like(comment)">顶{{ comment.up }}</span>
            <span class="comment-action" @click="dislike(comment)">踩{{ comment.down }}</span>
            <span 
              class="comment-action reply-btn" 
              @click="toggleReplyForm(index)"
            >
              回复
            </span>
            <span class="comment-action">分享</span>
          </div>
        </div>
        <!-- 简化后的回复框 -->
        <div class="reply-form" :style="{ display: activeReplyIndex === index ? 'block' : 'none' }">
          <input 
            type="text" 
            placeholder="写下你的回复..."
            ref="replyInput"
            @keyup.enter="submitReply"
          >
          <button class="reply-submit" @click="submitReply">回复</button>
        </div>
      </div>

      <div class="page custom-pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-size="page.pageSize"
          layout="total, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Comment',
  props: ['news_id'],
  data() {
    return {
      page: {
          currentPage: 1, // 当前页码
          pageSize: 5, // 每页显示的条数
          total: 0, // 默认 0 条，等待数据库渲染
      },
      commentContext: "",
      activeReplyIndex: -1,
      comments: [
        {
          commentId: 1,
          userPic: 'https://picsum.photos/32/32?random=1',
          userName: '魔都沂人[网易上海手机网友]',
          commentContent: '倒退的文明由特朗普导演。',
          commentTime: '昨天19:52',
          up: 225,
          down: 0
        },
        {
          commentId: 2,
          userPic: 'https://picsum.photos/32/32?random=2',
          userName: '封狼居[网易火星手机网友]',
          commentContent: '这条普老狗比哪条普疯狗更可恶。',
          commentTime: '昨天19:40',
          up: 153,
          down: 0
        },
        {
          commentId: 3,
          userPic: 'https://picsum.photos/32/32?random=3',
          userName: '正义态度网友[网易江苏无锡网友]',
          commentContent: '起因是川普把墨西哥湾改称美国湾，但美联社拒绝跟进依旧称墨西哥湾.白宫说不改名就不准进白宫，美联社已经到法院起诉',
          commentTime: '昨天21:03',
          up: 112,
          down: 0
        }
      ]
    }
  },
  methods: {
    handleSizeChange(val) {
        this.page.pageSize = val
        this.page.currentPage = 1
        console.log(this.page.pageSize);
        console.log(this.page.currentPage);
    },
    handleCurrentChange(val) {
        this.page.currentPage = val
        console.log(this.page.currentPage);
        this.getNewsComment()
    },
    submitComment() {
      if (!this.$store.state.user.isLogin) {
        this.$centerMessage({
          message: '未登录，无法发表评论',
          type: 'error'
        });
        return;
      }

      if (!this.commentContext.trim()) {
        this.$centerMessage({
          message: '评论内容不能为空',
          type: 'error'
        });
        return;
      }

      if (this.commentContext.length > 150) {
        this.$centerMessage({
          message: '字数过多',
          type: 'error'
        });
        return;
      }

      let commitCommentInfo = {
        userAccount: this.$store.state.user.userAccount,
        newsId: this.news_id,
        commentContext: this.commentContext
      }

      this.$api.serviceUser.post('api/user/commitComment', commitCommentInfo, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (response.data.code == 200){
          this.$centerMessage({
            message: '评论成功，等待评论审核通过',
            type: 'success'
          });
          this.commentContext = ''
        }
      })
      .catch(error => {
        console.error('失败', error);
      });
    },
    getNewsComment() {
      console.log({newsId: this.news_id, page: this.page});
      this.$api.serviceUser.post('api/user/allComments', 
      {newsId: this.news_id, page: this.page}, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (response.data.code == 200){
          this.comments = response.data.data.pageListData
          this.page.total = response.data.data.total

          this.$emit('total-comment', this.page.total);
        }
      })
      .catch(error => {
        console.error('失败', error);
      });
    },
    like(comment) {

      if (!this.$store.state.user.isLogin) {
        this.$centerMessage({
          message: '请先登录用户',
          type: 'error'
        });
        return;
      }

      let UserCommentClick = {
        commentId: comment.commentId,
        userAccount: this.$store.state.user.userAccount
      }
      console.log(UserCommentClick);
      this.$api.serviceUser.post('api/user/clickCommentLike', UserCommentClick, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (response.data.code == 200){
          comment.up = comment.up + 1
        }
        if (response.data.code == 40912){
          this.$centerMessage({
            message: response.data.message,
            type: 'error'
          });
        }
      })
      .catch(error => {
        console.error('失败', error);
      });
    },
    dislike(comment) {

      if (!this.$store.state.user.isLogin) {
        this.$centerMessage({
          message: '请先登录用户',
          type: 'error'
        });
        return;
      }

      let UserCommentClick = {
        commentId: comment.commentId,
        userAccount: this.$store.state.user.userAccount
      }
      this.$api.serviceUser.post('api/user/clickCommentDislike', UserCommentClick, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (response.data.code == 200){
          comment.down = comment.down + 1
          console.log(response.data);
        }
        if (response.data.code == 40912){
          this.$centerMessage({
            message: response.data.message,
            type: 'error'
          });
        }
      })
      .catch(error => {
        console.error('失败', error);
      });
    },
    toggleReplyForm(index) {
      if (this.activeReplyIndex === index) {
        this.activeReplyIndex = -1;
      } else {
        this.activeReplyIndex = index;
        this.$nextTick(() => {
          this.$refs.replyInput[index]?.focus();
        });
      }
    },
    submitReply() {
      // Handle reply submission here
      this.activeReplyIndex = -1;
    }
  },
  mounted() {
    this.getNewsComment()
  }
}
</script>

<style scoped>
.comment-container {
  max-width: 660px;
  margin: 0 auto;
  margin-top: 30px;
  background-color: #fff;
  /* padding: 15px; */
  /* box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); */
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 2px solid #ff4d4f;
  margin-bottom: 15px;
  width: 660px;
}

.comment-title {
  font-size: 18px;
  font-weight: bold;
  color: #222;
}

.comment-counts {
  display: flex;
  gap: 10px;
}

.comment-follow, .comment-join {
  font-size: 14px;
  color: #666;
}

.comment-login {
  font-size: 14px;
  color: #ff4e00;
  cursor: pointer;
}

.comment-notice {
  font-size: 14px;
  color: #999;
  margin: 10px 0;
  padding: 5px 0;
  float: left;
}

.comment-item {
  padding: 15px 0;
}

.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.comment-username {
  font-size: 14px;
  color: #666;
}

.comment-content {
  font-size: 16px;
  line-height: 1.5;
  margin-bottom: 15px;
}

.comment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-actions {
  display: flex;
  align-items: center;
}

.comment-action {
  margin-left: 15px;
  font-size: 12px;
  color: #666;
  cursor: pointer;
}

.comment-action:hover {
  color: #ff4e00;
}

.comment-up {
  color: #ff4e00;
}

.comment-form {
  border-radius: 4px;
  margin-bottom: 15px;
}

.comment-form textarea {
  width: 99%;
  background-color: rgba(227, 232, 237, 0.5);
  min-height: 80px;
  border: none;
  border-radius: 4px;
  resize: vertical;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  outline: none;
  resize: none;
}

.comment-submit {
  margin-top: 10px;
  padding: 6px 15px;
  background-color: #ff4e00;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  float: right;
}

.comment-submit:hover {
  background-color: #e64500;
}

.form-footer {
  overflow: hidden; /* 清除浮动 */
  border-bottom: 2px solid #ff4d4f;
}

/* 修改后的回复框样式 */
.reply-form {
  display: none;
  margin-top: 30px;
  position: relative;
}

.reply-form input {
  width: calc(100% - 80px);
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  outline: none; /* 移除选中时的边框 */
}

.reply-submit {
  height: 100%;
  margin-left: 10px;
  position: absolute;
  right: 0;
  top: 0;
  padding: 6px 15px;
  background-color: #ff4e00;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.reply-submit:hover {
  background-color: #e64500;
}

.page {
    height: 6%;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
}

.page /deep/ .el-pagination.is-background .el-pager li.active {
  background-color: #ff4d4f !important;
  color: white !important;
}

.page /deep/ .el-pagination.is-background .el-pager li:hover {
  color: #666;
}
</style>